package transport.netty.server;

import entity.RpcRequest;
import entity.RpcResponse;
import factory.SingleFacory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyServerHandler extends SimpleChannelInboundHandler<RpcRequest> {

    private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
    private static RequestHandler requestHandler;

    public NettyServerHandler() {
        requestHandler = SingleFacory.getSingle(RequestHandler.class);
    }

    //通道可读
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequest rpcRequest) throws Exception {
        logger.info("服务器接收到请求: {}", rpcRequest);
        logger.info("开始处理通道事件");
        //处理事件
        try {
            Object result = requestHandler.handle(rpcRequest);
            Channel channel = channelHandlerContext.channel();
            //通道活跃 写入数据到通道。
            if (channel.isActive() && channel.isWritable()) {
                channel.writeAndFlush(RpcResponse.success(result, rpcRequest.getRequestId()));
            } else {
                logger.error("通道不可写");
            }
        } finally {
            ReferenceCountUtil.release(rpcRequest);
        }
    }
}
